package up.android.json.calculadora;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

public class CalculadoraActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
	
		String url = "http://localhost:8080/AndroidServer/Calculadora";
		
		HttpClient http = new DefaultHttpClient();
		HttpPost post = new HttpPost(url);
		
		post.setHeader("Content-Type","application/json");
		
		try {
			JSONObject obj = new JSONObject();
			obj.put("par1", 2);
			obj.put("action", "sum");

			post.setEntity(new StringEntity(obj.toString()));
			HttpResponse response = http.execute(post);
			InputStream in = response.getEntity().getContent();

			InputStreamReader reader = new InputStreamReader(in);
			BufferedReader b = new BufferedReader(reader);
			String s = "";
			String line;
			while((line = b.readLine())!= null)
				s+=line+"\n";

			JSONObject result = new JSONObject(s);
			Toast t = Toast.makeText(getApplicationContext(), "Resultado: "+result.getString("result"), Toast.LENGTH_LONG);
			t.show();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			Log.e("Componentes",e.getMessage(),e);
		} 
	}
	
}
